package org.example.judge_comment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import org.example.judge_comment.entity.RequestMailParams;
import org.example.judge_comment.mapper.MailMapper;
import org.example.judge_comment.service.MailService;
import org.example.judge_common.entity.PageResult;
import org.example.judge_common.entity.RequestParams;
import org.example.judge_common.util.IdWorker;
import org.example.judge_common.util.MyUtils;
import org.example.judge_pojo.Mail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.function.Consumer;

@Service("MailServiceImpl")
public class MailServiceImpl extends ServiceImpl<MailMapper, Mail> implements MailService {
    @Autowired
    private IdWorker idWorker;
    @Override
    public PageResult<Mail> search(RequestMailParams params) {
//        if(MyUtils.isEmpty(params.getField())){ //默认排序字段
            params.setField("create_time");
//        }
        if(MyUtils.isEmpty(params.getOrder())){   //默认排序方式
            params.setOrder(RequestParams.DESC);
        }

        QueryWrapper<Mail> queryWap = new QueryWrapper<>();

        //字段模糊匹配
        if(MyUtils.isNotEmpty(params.getKey())){
            queryWap.and(new Consumer<QueryWrapper<Mail>>() { //隔离or条件
                @Override
                public void accept(QueryWrapper<Mail> problemQueryWrapper) {
                    problemQueryWrapper.like("`text`",params.getKey());
                }
            });

        }
        //发送方
        if(MyUtils.isNotEmpty(params.getUserId()))
            queryWap.eq(true,"user_id",params.getUserId());
        else queryWap.ne("user_id","1"); //默认不包括系统消息
        //接收方

        queryWap.eq(MyUtils.isNotEmpty(params.getTo()),"`to`",params.getTo());
        //比赛ID
//        if(params.getKey()!=null)queryWap.eq("contest_id",params.getKey());


        //排序
        queryWap.orderBy(true,"asc".equalsIgnoreCase(params.getOrder()),params.getField());


        //设置分页
        PageHelper.startPage(params.getPage(), params.getSize(),false);
        List<Mail> problems = this.baseMapper.selectList(queryWap);
        //求数据条数
        Integer count = this.baseMapper.selectCount(queryWap);

        return new PageResult<Mail>(count.longValue(),problems);
    }

    @Override
    public boolean save(Mail entity) {
        entity.setId(idWorker.nextId().toString());
        entity.setCreateTime(new Date());
        entity.setRead(0);
        if(MyUtils.isEmpty(entity.getTitle())&&"1".equals(entity.getUserId())){//系统通知
            entity.setTitle("系统通知");
        }
        return super.save(entity);
    }

}
